package com.hit.client.driver.util;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

public class GfCacheUtil {

    public static final String KEY_ROBOT_STATUS = "robotStatus";
    public static final String KEY_ROBOT_STATUS_OF_CAR = "robotStatusOfCar";

    private static final Cache<String, Boolean> speedFlagCache = CacheBuilder.newBuilder()
            .expireAfterWrite(600, TimeUnit.MICROSECONDS) // 缓存过期时间
            .build();

    private static final Cache<String, Object> cache = CacheBuilder.newBuilder()
            .expireAfterWrite(5, TimeUnit.SECONDS) // 缓存过期时间
            .build();

    private static final Cache<String, Object> longtimeCache = CacheBuilder.newBuilder()
            .expireAfterWrite(60, TimeUnit.SECONDS) // 缓存过期时间
            .build();

    public static void setSpeedFlag(String serialNumber) {
        speedFlagCache.put(generateFinalKey(serialNumber, "speed"), true);
    }

    public static boolean getSpeedFlag(String serialNumber) {
        return Optional.ofNullable(speedFlagCache.getIfPresent(generateFinalKey(serialNumber, "speed"))).orElse(false);
    }

    public static void setCarSpeedFlag(String serialNumber) {
        speedFlagCache.put(generateFinalKey(serialNumber, "car_speed"), true);
    }

    public static boolean getCarSpeedFlag(String serialNumber) {
        return Optional.ofNullable(speedFlagCache.getIfPresent(generateFinalKey(serialNumber, "car_speed"))).orElse(false);
    }

    public static void put(String serialNumber, String key, Object value) {
        cache.put(generateFinalKey(serialNumber, key), value);
    }

    public static Object get(String serialNumber, String key) {
        return cache.getIfPresent(generateFinalKey(serialNumber, key));
    }

    public static void putLongtimeCache(String serialNumber, String key, Object value) {
        longtimeCache.put(generateFinalKey(serialNumber, key), value);
    }

    public static Object getLongtimeCache(String serialNumber, String key) {
        return longtimeCache.getIfPresent(generateFinalKey(serialNumber, key));
    }

    private static String generateFinalKey(String serialNumber, String key) {
        return serialNumber + "@" + key;
    }

}
